#!usr/bin/env python
# -*- coding: utf-8 -*-

# import requests
from PIL import Image
import pytesseract
# import re
import json, sys, os, codecs, chardet

import time
import numpy as np
import threading
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains

userName = ''
passWord = ''

imgUrl = 'http://kq.neusoft.com/imageRandeCode'
urlLogin = 'http://kq.neusoft.com/login.jsp'
urlRecord = 'http://kq.neusoft.com/record.jsp'
urlAttendance = 'http://kq.neusoft.com/attendance.jsp'

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36',
    'Cookie': 'JSESSIONID=l8ygby2Gv2969tLWZP87KVfLcxxvvbV5s092wStvj1MMx12TTq2c!-1919813840'
}

# 识别数字的验证码
def getYanZhengNum(im):

    im.load()
    imgry = im.convert('L')
    # imgry.save('L.png')


    threshold = 140
    table = []
    for i in range(256):
        if i < threshold:
            table.append(0)
        else:
            table.append(1)
    out = imgry.point(table, '1')
    # out.save('n1.png')
    # out.show()
    num = pytesseract.image_to_string(out)
    print('code: ' + num)
    return num


# 滑块拖动的验证码，根据图片计算图片需要拖动的距离
def calcXspace(img):
	imgData = np.array(img)

	rows, cols = imgData.shape
	# print(rows, cols)
	save_data = []
	# 想按着列方向 取数据，需要固定x，y递增
	for x in range(cols):
		save_data.append(0)
		for y in range(rows):
			if (imgData[y, x] > 240):
				save_data[x] = save_data[x] + 1

	# 62 表示跳过第一个图形
	for i in range(cols):
		if i>62 and save_data[i] > 15:
			print('calc result=',i, save_data[i])
			return i

	return 0

def downImg():
    print("downImg")
    img = driver.find_element_by_xpath("//img[@id='bigImage']")

    left = int(img.location['x'])
    top = int(img.location['y'])
    right = int(left + img.size['width'])
    bottom = int(top + img.size['height'])

    print((left, top, right, bottom))

    driver.save_screenshot('screenshot.png')

    im = Image.open('screenshot.png')
    im = im.crop((left, top, right, bottom))
    im.save('num.jpg')

    new_im = im.convert('L')
    new_im.save('numL.jpg')

    num = calcXspace(new_im)

    print("numX=", num)

    # 验证-滑块，有20px的偏差，因为滑块40宽度，需要拖拽到一半后才产生移动效果
    slider_btn = driver.find_element_by_xpath("//div[@class='ui-slider-btn init ui-slider-no-select']")
    action = ActionChains(driver)
    action.drag_and_drop_by_offset(slider_btn, (num+20), 0).perform()
    time.sleep(1)

    submit = driver.find_element_by_id('loginButton')
    submit.click()

    # 2
    try:
        # second page
        WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, 'mr36')))
        time.sleep(1)
        trs = driver.find_elements_by_tag_name('tr')
        print(u'build ' + str(len(trs)-1) + u'times')
        submit2 = driver.find_element_by_xpath("//a[@class='mr36']")
        submit2.click()

        print(userName + u' exit')
        time.sleep(2)
        driver.quit()

    except:
        time.sleep(2)
        # main()


def handleOnePage():
    WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.CLASS_NAME, 'textfield')))
    time.sleep(1)

    input_name = driver.find_elements_by_xpath("//input[@class='textfield userName']")
    input_password = driver.find_elements_by_xpath("//input[@class='textfield password']")
    # print(inputs)

    input_name[0].clear()
    input_name[0].send_keys(userName)
    time.sleep(1)

    input_password[0].clear()
    input_password[0].send_keys(passWord)
    time.sleep(1)

    #按住左键,显示验证图
    slider_btn = driver.find_element_by_xpath("//div[@class='ui-slider-btn init ui-slider-no-select']")
    action = ActionChains(driver)
    action.click_and_hold(slider_btn).perform()

    time.sleep(0.1)
    print("star down img")
    t1 = threading.Thread(target=downImg)
    t1.start()
    # print(img)

def main():
    handleOnePage()


def init():
    # read
    global userName, passWord

    if userName == "" and len(sys.argv) < 3:
        sys.exit(0)
    elif userName != "":
        pass
    else:
        userName = sys.argv[1]
        passWord = sys.argv[2]

if __name__ == '__main__':
    init()
    print(userName + u' login')

    desired_capabilities = dict(DesiredCapabilities.PHANTOMJS)
    desired_capabilities["phantomjs.page.settings.userAgent"] = ("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36")
    # dcap['phantomjs.page.settings.cookie'] = ("JSESSIONID=J6cZb98pVs5Mvm4TX58kvjyQCshPP9h1bM9hWGvyTcy6tZP3xs2z!-1919813840")

    options = webdriver.ChromeOptions()
    options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"])
    driver =webdriver.Chrome(executable_path='chromedriver.exe', chrome_options=options, desired_capabilities=desired_capabilities)    #service_args=['--ssl-protocol=any',]

    driver.set_page_load_timeout(10)

    driver.get('http://kq.neusoft.com/')

    main()






